package com.uroad.liaoningpos.service;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.newland.aidl.deviceService.AidlDeviceService;
import com.newland.aidl.scanner.AidlScanner;
import com.uroad.liaoningpos.activity.MainActivity;

import static android.content.Context.BIND_AUTO_CREATE;


/**
 * Author by bxy, Date on 2019/4/10 0010.
 */
public class DeviceService {

    private static AidlDeviceService deviceService;

    private Context context;
    public DeviceService(Context context) {
        this.context = context;
    }

    public void connect(){
        SDKExecutors.getThreadPoolInstance().submit(new Runnable() {
            @Override
            public void run() {
                if (deviceService == null) {
                    Intent intent = new Intent();
                    intent.setPackage("com.newland.mtype.service"); // 使用服务apk的时候使用
//                    intent.setPackage(context.getPackageName()); //使用arr的时候使用
                    intent.setAction("com.newland.DeviceService");
                    context.bindService(intent, serviceConnection, BIND_AUTO_CREATE);


                } else {


                }
            }
        });
    }

    public void disconnect(){
        SDKExecutors.getThreadPoolInstance().submit(new Runnable() {
            @Override
            public void run() {
                if (deviceService != null) {
                    try {
                        context.unbindService(serviceConnection);
                    } catch (Exception e) {
                        e.printStackTrace();


                    } finally {
                        deviceService = null;
                        ((MainActivity)context).setConnectState(false);


                    }

                } else {

                }
            }
        });
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            deviceService = null;
            ((MainActivity)context).setConnectState(false);
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            deviceService = AidlDeviceService.Stub.asInterface(service);
            ((MainActivity)context).setConnectState(true);
        }
    };

    public static AidlScanner getScanner() {
        try {
            return AidlScanner.Stub.asInterface(deviceService.getScanner());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
